﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Agro.Models;

namespace Agro.Services {

    public class PermissionService : BaseService, IPermissionService {

        /// <summary>
        /// 用户是否有权限
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="actionCode"></param>
        /// <returns></returns>
        public bool HasPremission(string userId, string actionCode) {
            T_User user = DB.Single<T_User>(T_User._.User_ID == userId);
            if (user.IsAdmin()) return true;

            IList<T_UserAction> userActionList = DB.From<T_UserAction>()
                .InnerJoin<T_Action>(T_Action._.ActionID == T_UserAction._.ActionID)
                .Where(T_UserAction._.UserID == userId && T_Action._.ActionCode == actionCode).ToList();
            if (userActionList.Count > 0) return true;

            var userRoleList = DB.From<T_User_Role>().Where(T_User_Role._.UR_UserID == userId).ToList();
            if (userRoleList.Count == 0) return false;
            var roleActionList = DB.From<T_Action>().InnerJoin<T_RoleAction>(T_RoleAction._.ActionID == T_Action._.ActionID)
                .Where(T_RoleAction._.RoleID.In(userRoleList.Select(m => m.UR_RoleID).ToArray())).ToList();
            return roleActionList.Count(m => m.ActionCode == actionCode) > 0;
        }
    }
}
